﻿using LibraryHub.Core.Models.Book;
using LibraryHub.Core.Models.User;
using LibraryHub.DataAccess;
using IndexModel = LibraryHub.Core.Models.Book.IndexModel;

namespace LibraryHub.BusinessLogic
{
    public class BooksBl
    {
        #region Constants

        private const int takeBookDaysMinimum = 1;
        private const int takeBookDaysMaximum = 14;

        #endregion

        #region Fields

        private readonly BooksDa bookDao = new BooksDa();
        private readonly UsersDa userDao = new UsersDa();

        #endregion

        public IndexModel Index()
        {
            var model = new IndexModel();
            var books = bookDao.GetBooksList();
            model.Books = books;

            return model;
        }

        public bool CreateBook(BookModel book)
        {
            bool result = bookDao.AddBook(book);

            return result;
        }

        public BookModel FindBook(int id)
        {
            var model = bookDao.FindBook(id);

            return model;
        }

        public bool EditBook(BookModel book)
        {
            bool result = bookDao.EditBook(book);

            return result;
        }

        public bool TakeBook(TakeBookModel takeBook)
        {
            // That's how every BusinessLayer method should be done.
            // Should not pass consistency checks to DataAccessLayer
            // since it should be easy to replace etc.
            if (takeBook.TakeBookDays < takeBookDaysMinimum || takeBook.TakeBookDays > takeBookDaysMaximum)
            {
                return false;
            }

            var user = userDao.FindUserByLogin(takeBook.User.Login);
            if (user == null || user.Role != UserRoleEnum.Reader)
            {
                return false;
            }
            takeBook.User = user;

            var book = bookDao.FindBook(takeBook.Book.Id);
            if (book == null || book.IsTaken)
            {
                return false;
            }
            takeBook.Book = book;

            bool result = bookDao.TakeBook(takeBook); //TODO: add maximum taken books validation.
            return result;
        }

        #region Return

        public ReturnBookModel GetReturnBookInfo(int id)
        {
            var model = bookDao.GetReturnBookInfo(id);

            return model;
        }

        public bool ReturnBook(int id)
        {
            var book = FindBook(id);
            if (book == null || !book.IsTaken)
            {
                return false;
            }

            bool result = bookDao.ReturnBook(id);

            return result;
        }

        #endregion

        public bool DeleteBook(int id)
        {
            bool result = bookDao.DeleteBook(id);

            return result;
        }
    }
}
